<template>
  <el-dialog
    fullscreen
    :title="type == 1 ? '试卷预览' : '正在考试'"
    :visible="open"
    append-to-body
    @close="onClose"
    @open="onOpen"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="true"
  >
    <div class="exam-box">
      <div class="exam-body">
        <el-form ref="form" :model="form" label-width="120px">
          <div class="exam-content">
            <div class="exam-content-right">
              <el-card class="box-card">
                <div class="ans-title">答题卡</div>
                <template v-for="(item, index) in answers">
                  <div v-if="item.question.length" :key="index">
                    <div class="ans-type">
                      {{ item.type | formatType }}
                      <span style="float: right;"
                        >共{{ item.question.length }}题,合计{{
                          item.question.length * form[scoreFields[item.type]]
                        }}分</span
                      >
                    </div>
                    <div class="ans-items">
                      <div
                        class="ans-item"
                        :class="{ active: question.answered }"
                        v-for="question in item.question"
                        :key="question.index"
                      >
                        {{ question.index + 1 }}
                      </div>
                    </div>
                  </div>
                </template>
              </el-card>
              <el-card
                v-if="type == 2"
                class="box-card"
                style="margin-top:20px;"
              >
                <div class="times-tips">剩余考试时间</div>
                <div>
                  <count-down
                    v-if="open"
                    class="times-count"
                    :endTime="examEndTime"
                    :callback="onTimeEnd"
                    endText="已经结束了"
                    ref="countDown"
                  ></count-down>
                </div>
              </el-card>
              <el-card
                v-if="type == 2"
                class="box-card"
                style="margin-top:20px;"
              >
                <el-button
                  style="display:block;margin:20px auto;"
                  type="warning"
                  @click="onJiaoJuan"
                  :disabled="jiaoJuanLoading"
                  >提交试卷</el-button
                >
                <el-button
                  style="display:block;margin:20px auto;"
                  type="danger"
                  @click="$emit('close')"
                  >放弃考试</el-button
                >
              </el-card>
            </div>
            <div class="exam-content-left">
              <el-card class="box-card">
                <div v-for="(item, index) in questions" :key="index">
                  <!-- 选择题 -->
                  <div v-if="item.type == 0" class="exam-item">
                    <div class="exam-item-title">
                      <div class="exam-no">{{ index + 1 }}.</div>
                      <div>
                        <span class="exam-score-span"
                          >({{ form.chooseScore }}分)</span
                        >{{ item.title }}
                      </div>
                    </div>
                    <div>
                      <div class="exam-item-value">
                        <div
                          v-for="(option, idx) in item.options"
                          :key="idx"
                          class="exam-item-select"
                        >
                          <el-radio
                            v-if="item.isSingle"
                            :disabled="type == 1"
                            :label="true"
                            :value="option.checked"
                            @change="
                              e =>
                                onAnswerChange(item.type, index, true, e, idx)
                            "
                            >选项{{ idx | filterIndexToABC }}:
                            {{ option.label }}</el-radio
                          >
                          <el-checkbox
                            v-else
                            :disabled="type == 1"
                            v-model="option.checked"
                            :label="option.label"
                            @change="onAnswerChange(item.type, index)"
                            >选项{{ idx | filterIndexToABC }}:
                            {{ option.label }}</el-checkbox
                          >
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 填空题 -->
                  <div v-if="item.type == 1" class="exam-item">
                    <div class="exam-item-title">
                      <div class="exam-no">{{ index + 1 }}.</div>
                      <div>
                        <span class="exam-score-span"
                          >({{ form.fillInTheBlankScore }}分)</span
                        >请填空
                      </div>
                    </div>
                    <div class="fill-empty">
                      <template v-for="(text, textIdx) in item.titles">
                        <div v-if="text === '�'" :key="'�' + textIdx">
                          <el-input
                            :readonly="type == 1"
                            class="fill-input"
                            v-model="item.values[textIdx]"
                            @change="onAnswerChange(item.type, index)"
                          />
                        </div>
                        <div v-else :key="textIdx">{{ text }}</div>
                      </template>
                    </div>
                  </div>
                  <!-- 问答题 -->
                  <div v-if="item.type == 2" class="exam-item">
                    <div class="exam-item-title">
                      <div class="exam-no">{{ index + 1 }}.</div>
                      <div>
                        <span class="exam-score-span"
                          >({{ form.otherScore }}分)</span
                        >{{ item.title }}
                      </div>
                    </div>
                    <el-input
                      :readonly="type == 1"
                      type="textarea"
                      v-model="item.answers"
                      placeholder="请输入答案"
                      @change="onAnswerChange(item.type, index)"
                    />
                  </div>
                </div>
              </el-card>
              <el-card
                v-if="type == 1"
                class="box-card"
                style="margin-top:20px;"
              >
                <!-- <el-button
                  style="display:block;margin:20px auto;"
                  type="warning"
                  @click="onJiaoJuan"
                  :disabled="jiaoJuanLoading"
                  >提交试卷</el-button
                > -->
                <el-button
                  style="display:block;margin:20px auto;"
                  type="danger"
                  @click="$emit('close')"
                  >关闭预览</el-button
                >
              </el-card>
            </div>
          </div>
        </el-form>
      </div>

      <!-- <div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="$emit('close')">提交试卷</el-button>
          <el-button @click="$emit('close')">放弃考试</el-button>
        </div>
      </div> -->
    </div>
  </el-dialog>
</template>

<script>
function delHtmlTag(str) {
  //去掉所有的html标记
  return str.replace(/<[^>]+>/g, "");
}
// a.match(/<u[^>]*>([\s\S]*?)<\/u>/g)
// a.replace(/<u[^>]*>([\s\S]*?)<\/u>/g,"�")
import { getExam } from "@/api/cms/exma";
const reg = /<u[^>]*>([\s\S]*?)<\/u>/g;
import CountDown from "@/components/countDown";
import { batchRecord, startExam } from "@/api/cms/record";

export default {
  components: {
    CountDown
  },
  props: {
    id: {
      type: String | Number,
      default: ""
    },
    type: {
      type: String | Number,
      default: 1 // 1预览 2考试
    },
    open: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: "试卷预览"
    }
  },
  data() {
    return {
      form: {},
      questions: [],
      answers: [
        { type: 0, question: [] },
        { type: 1, question: [] },
        { type: 2, question: [] }
      ],
      examEndTime: "",
      scoreFields: ["chooseScore", "fillInTheBlankScore", "otherScore"],
      scoreId: "",
      jiaoJuanLoading: false
    };
  },
  filters: {
    formatType(type) {
      switch (type) {
        case 0:
          return "选择题";
        case 1:
          return "填空题";
        case 2:
          return "问答题";
      }
    },
    filterIndexToABC(index) {
      return String.fromCharCode(65 + index);
    }
  },
  created() {},
  methods: {
    onClose() {
      this.form = {};
      this.examEndTime = "";
      this.$emit("close");
    },
    onOpen() {
      if (!this.id) return;
      getExam(this.id).then(response => {
        const questions = response.data.cmsExamQuestionList.map(x => {
          if (x.type == 0) {
            const answers = x.answer.split("�");
            const options = x.options.split("�").map(item => {
              if (this.type == 2) {
                //考试
                return {
                  label: item,
                  checked: false
                };
              }
              // 带答案 预览
              return {
                label: item,
                checked: answers.indexOf(item) > -1 ? true : false
              };
            });
            return {
              id: x.id,
              type: 0, // 0 , 1, 2, 3
              title: x.title,
              options,
              isSingle: answers.length == 1
            };
          }

          if (x.type == 1) {
            const texts = delHtmlTag(x.options);
            const titles = texts.split("�").filter(item => !!item);
            console.log("texts", texts, texts[0], texts[texts.length - 1]);
            const values = x.title
              .match(/<u[^>]*>([\s\S]*?)<\/u>/g)
              .map(delHtmlTag);
            console.log(titles, values);
            let j = 0;
            let ques = [];
            let ans = [];
            let isAnsFirst = false;
            if (texts[0] == "�") {
              isAnsFirst = true;
              // ques.push("�");
              // ans.push(values[j]);
              // j++;
            }
            let l = Math.min(titles.length, values.length);
            for (let i = 0; i < l; i++) {
              if (isAnsFirst) {
                ques.push("�");
                ans.push(values[i]);

                ques.push(titles[i]);
                ans.push("");
              } else {
                ques.push(titles[i]);
                ans.push("");

                ques.push("�");
                ans.push(values[i]);
              }
              // ques.push(titles[i]);
              // ques.push("�");

              // ans.push("");
              // ans.push(values[j]);
              // j++;
            }
            if (titles.length > values.length) {
              ques.push(titles[titles.length-1]);
              ans.push("");
            } else if (titles.length < values.length) {
              ques.push("�");
              ans.push(values[values.length-1]);
            }

            // if (titles.length == 1) {
            //   ques.push(titles[0]);
            //   ans.push("");
            // }
            // if (texts[texts.length - 1] == "�") {
            //   ques.push("�");
            //   ans.push(values[j]);
            // }

            return {
              id: x.id,
              type: 1,
              title: x.title,
              titles: ques,
              values: this.type == 2 ? [] : ans
            };
          }
          if (x.type == 2) {
            return {
              id: x.id,
              type: 2,
              title: x.title
            };
          }
        });
        this.questions = questions;

        // 答题卡处理
        const answers = [
          { type: 0, question: [] },
          { type: 1, question: [] },
          { type: 2, question: [] }
        ];
        this.questions.forEach((item, index) => {
          if (item.type === 0) {
            answers[0].question.push({ index, answered: false });
          } else if (item.type === 1) {
            answers[1].question.push({ index, answered: false });
          } else if (item.type === 2) {
            answers[2].question.push({ index, answered: false });
          }
        });
        this.answers = answers;

        this.form = response.data;
        this.form.times = [response.data.startDate, response.data.endDate];
        this.form.timeType = response.data.duration ? 1 : 0;

        if (this.type == 2) {
          this.onStartExam(); //开始考试
        }
      });
    },
    onTimeEnd() {
      this.onJiaoJuan();
    },
    onAnswerChange(type, index, isSingle = false, e, isSingleIndex) {
      const answersIndex = this.answers[type].question.findIndex(
        x => x.index === index
      );
      if (type === 0) {
        if (isSingle) {
          console.log(e);
          // 单选
          this.questions[index].options.forEach((item, i) => {
            item.checked = !e && i === isSingleIndex ? true : false;
          });
        }

        // }else{
        //   //多选
        const checked = this.questions[index].options.filter(
          item => item.checked
        );
        if (checked.length > 0) {
          this.answers[type].question[answersIndex].answered = true;
        } else {
          this.answers[type].question[answersIndex].answered = false;
        }
        // }
      } else if (type === 1) {
        console.log(this.questions[index]);
        if (
          this.questions[index].titles.filter(x => x === "�").length ===
          this.questions[index].values.filter(x => x !== "" && x !== undefined)
            .length
        ) {
          this.answers[type].question[answersIndex].answered = true;
        } else {
          this.answers[type].question[answersIndex].answered = false;
        }
      } else if (type === 2) {
        if (this.questions[index].title) {
          this.answers[type].question[answersIndex].answered = true;
        } else {
          this.answers[type].question[answersIndex].answered = false;
        }
      }
    },
    onSubmit() {
      if (this.questions.some(x => !x.title)) {
        this.$message.error("请填写题目");
        return false;
      }

      if (
        this.questions
          .filter(x => x.type === 0)
          .some(x => x.options.filter(y => y.checked && y.label).length < 1)
      ) {
        this.$message.error("请填写选项");
        return false;
      }

      if (
        this.questions
          .filter(x => x.type === 1)
          .some(y => !y.title.match(reg) || y.title.match(reg).length < 1)
      ) {
        this.$message.error("请划填空题答案");
        return false;
      }
      this.questions
        .filter(x => x.type == 0)
        .forEach(x => {
          x.answers = [];
          x.options2 = [];
          x.options.forEach(x => {
            x.options2.push(x.label);
            if (x.checked) {
              x.answers.push(x.label);
            }
          });
        });
      this.questions
        .filter(x => x.type == 1)
        .forEach(x => {
          x.answers = x.title
            .match(reg)
            .map(y => y.replace(/<u[^>]*>([\s\S]*?)<\/u>/g, "$1"));
          x.showTitle = x.title.replace(reg, "�");
        });
      console.log(this.form);
      console.log(this.questions);
    },
    onStartExam() {
      startExam(this.id)
        .then(res => {
          this.scoreId = res.data.scoreId;
          this.examEndTime =
            new Date(res.data.startTime).getTime() +
            this.form.duration * 60 * 1000;
          this.$nextTick(() => {
            this.$refs.countDown.start();
          });
          // this.$message.success("开始考试成功");
        })
        .catch(err => {
          // this.$message.error("开始考试失败");
        });
    },
    onJiaoJuan() {
      if (this.type == 1) {
        this.$emit("close");
        return;
      }
      if (this.jiaoJuanLoading) return;
      const p = {
        examId: this.id,
        scoreId: this.scoreId
      };

      const list = this.questions.map(x => {
        if (x.type == 0) {
          return {
            answer: x.options
              .filter(y => y.checked)
              .map(y => y.label)
              .join("�"),
            examId: this.id,
            questionId: x.id
          };
        }
        if (x.type == 1) {
          return {
            answer: x.values.filter(y => y !== "").join("�"),
            examId: this.id,
            questionId: x.id
          };
        }
        if (x.type == 2) {
          return {
            answer: x.answers,
            examId: this.id,
            questionId: x.id
          };
        }
      });
      p.cmsExamRecordList = list;
      console.log(p);
      // return;
      this.jiaoJuanLoading = true;
      batchRecord(p)
        .then(res => {
          this.jiaoJuanLoading = false;
          this.$message.success("交卷成功");
          this.$emit("close");
          this.$emit("endexam");
        })
        .catch(err => {
          this.jiaoJuanLoading = false;
          this.$message.error("交卷失败");
        });
    },
    submitForm() {},
    cancel() {}
  }
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-dialog__body {
    height: calc(100% - 55px);
  }

  .fill-input .el-input__inner {
    border-top: 0 !important;
    border-right: 0 !important;
    border-left: 0 !important;
    border-radius: 0 !important;
  }
  .exam-item-select {
    .el-radio__label,.el-checkbox__label{
      white-space: break-spaces;
    }
    .el-radio__label{
      line-height: 19px;
    }
    .el-checkbox__label{
      display: inline;
    }
  }
}

.exam-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  .exam-body {
    flex: 1;
    height: 100%;
    .el-form {
      height: 100%;
    }
  }
}
.exam-content {
  display: flex;
  align-items: flex-start;
  height: 100%;
  .exam-content-right {
    width: 200px;
    // border-radius: 10px;
    // border: 1px solid #ccc;
  }
  .exam-content-left {
    margin: 0 20px;
    flex: 1;
    height: 100%;
    overflow-y: auto;
  }
}
@media (max-width: 767px) {
  .el-form {
    height: auto !important;
  }
  .exam-content {
    display: flex;
    flex-direction: column;
    // align-items: flex-start;
    .exam-content-right {
      width: calc(100% - 0px);
      margin: 20px 0;
      box-sizing: border-box;
    }
    .exam-content-left {
      width: calc(100% - 0px);
      margin: 0 0px 50px 0;
    }
  }
}
.exam-item {
  border: 1px solid #ccc;
  margin-bottom: 20px;
  border-radius: 20px;
  padding: 20px;
  .exam-item-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-weight: bold;
    .exam-no {
      margin-right: 10px;
      font-size: 18px;
      // color: #000;
      color: #0a84ff;
      font-style: italic;
      font-weight: 700;
    }
  }
  .exam-score-span {
    font-size: 14px;
    color: #303133;
    font-style: normal;
    font-weight: bold;
    margin: 0 4px;
  }
  .exam-item-value {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .exam-item-select {
    display: flex;
    align-items: center;
    margin-right:10px;
  }
}
.times-tips {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
}
.times-count {
  color: rgb(255, 0, 0);
  font-weight: 700;
  font-size: 16px;
}
.ans-title {
  font-size: 18px;
}
.ans-type {
  font-size: 14px;
  font-weight: 700;
  padding: 10px 0px 10px 0px;
}
.ans-items {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.ans-item.active {
  color: #fff;
  background: #1890ff;
}
.ans-item {
  border-radius: 2px;
  color: #555;
  background: #eee;
  width: 30px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  margin-right: 6px;
}
.fill-empty {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>
